# coding:utf-8

import os
import json
import urllib

import qrcode
from flask import url_for
from PIL import Image, ImageDraw, ImageFont

from app.op.constant import (
    FeedbackStatus, DemandStatus, UserLevel
)
from common.models import Feedback
from app.wechat.models import WechatTemplate, WechatMenu
from app.wechat.constant import WxMenu


def generate_review_fail_content(user, host, reason):
    """
    created by chenhj at 2017/7/26

    """
    t = WechatTemplate.get_by_args(code='review_fail')
    info_url = urllib.parse.urljoin(host, '#user/JoinSupplier?login_bind=1')
    info_url = '{host}?redirect_url={url}'.format(
        host=url_for('api_bp.wx_login', _external=True),
        url=urllib.parse.quote_plus(info_url)
    )
    # oauth = generate_wechat_oauth(url)
    data = t.content.replace(
        'keyword1_value', user.nickname
    ).replace(
        'keyword2_value', user.created_datetime.strftime('%F %T')
    ).replace(
        'keyword3_value', reason
    )

    return t.template_code, json.loads(data), info_url
    # return t.template_code, json.loads(data), oauth.authorize_url


def generate_gift_pack_content(user, host, pack, bid_point):
    """
    created by chenhj at 2017/8/28

    """
    t = WechatTemplate.get_by_args(code='gift_pack_notification')
    gift_url = urllib.parse.urljoin(host, '#pack/MyPack?login_bind=1')
    gift_url = '{host}?redirect_url={url}'.format(
        host=url_for('api_bp.wx_login', _external=True),
        url=urllib.parse.quote_plus(gift_url)
    )
    # oauth = generate_wechat_oauth(url)
    data = t.content.replace(
        'first_value3', ''
    ).replace(
        'first_value', '{}个汇币'.format(str(bid_point))
    ).replace(
        'keyword1_value', user.mobile
    ).replace(
        'keyword2_value', '无使用期限'
    )

    return t.template_code, json.loads(data), gift_url
    # return t.template_code, json.loads(data), oauth.authorize_url


def generate_invite_gift_pack_content(user, host, bill, nickname):
    """
    created by chenhj at 2017/8/28

    """
    t = WechatTemplate.get_by_args(code='invite_gift_pack_notification')
    gift_url = urllib.parse.urljoin(host, '#pack/MyPack?login_bind=1')
    gift_url = '{host}?redirect_url={url}'.format(
        host=url_for('api_bp.wx_login', _external=True),
        url=urllib.parse.quote_plus(gift_url)
    )
    # oauth = generate_wechat_oauth(url)
    data = t.content.replace(
        'first_value1', str(bill.bid_point)
    ).replace(
        'first_value2', nickname
    ).replace(
        'first_value3', str(bill.amt)
    ).replace(
        'keyword1_value', user.mobile
    ).replace(
        'keyword2_value', '无'
    )

    return t.template_code, json.loads(data), gift_url
    # return t.template_code, json.loads(data), oauth.authorize_url


def generate_finish_img_checked_content(demand, host, inc_credit):
    """
    add by zhouhl 2017-09-08
    生成结项图片审核通过内容，供推送微信消息使用
    """
    t = WechatTemplate.get_by_args(code='finish_img_notify')
    demand_url = urllib.parse.urljoin(
        host, '#DemandDetail?did={d_id}&login_bind=1'.format(d_id=demand.id)
    )
    demand_url = '{host}?redirect_url={url}'.format(
        host=url_for('api_bp.wx_login', _external=True),
        url=urllib.parse.quote_plus(demand_url)
    )
    # oauth = generate_wechat_oauth(url)
    data = t.content.replace(
        'first_value', '您申报的信息已审核通过\\n'
    ).replace(
        'keyword1_value', '{prov}{city}{type}{cate}项目'.format(
            prov=demand.prov,
            city=demand.city,
            type=demand.type_display,
            cate=demand.cate_display,
        )
    ).replace(
        'keyword2_value', '审核通过'
    ).replace(
        'remark_value', '\\n成就值+{inc_credit}，查看项目详细↓↓↓'.format(
            inc_credit=inc_credit
        )
    )
    return t.template_code, json.loads(data), demand_url
    # return t.template_code, json.loads(data), oauth.authorize_url


def generate_finish_img_invalid_content(demand, host):
    """
    add by zhouhl 2017-09-08
    生成结项图片审核不通过内容，供推送微信消息使用
    """
    t = WechatTemplate.get_by_args(code='finish_img_notify')
    demand_url = urllib.parse.urljoin(
        host, '#DemandDetail?did={d_id}&login_bind=1'.format(d_id=demand.id)
    )
    demand_url = '{host}?redirect_url={url}'.format(
        host=url_for('api_bp.wx_login', _external=True),
        url=urllib.parse.quote_plus(demand_url)
    )
    # oauth = generate_wechat_oauth(url)
    data = t.content.replace(
        'first_value', '您申报的信息审核不通过\\n'
    ).replace(
        'keyword1_value', '{prov}{city}{type}{cate}项目'.format(
            prov=demand.prov,
            city=demand.city,
            type=demand.type_display,
            cate=demand.cate_display,
        )
    ).replace(
        'keyword2_value', '审核不通过'
    ).replace(
        'remark_value', '\\n点击查看项目详细↓↓↓'
    )
    return t.template_code, json.loads(data), demand_url
    # return t.template_code, json.loads(data), oauth.authorize_url


def generate_menu_pid_choice(menu_id=None):
    """
    created by chenhj at 2017/8/3
    生成父菜单选择下拉
    """
    menus = WechatMenu.get_list_by_args(pid=0, type=WxMenu.PARENT_BUTTON.value)
    base_menu = [(0, '无')]
    if not menu_id:
        base_menu.extend([(menu.id, menu.name) for menu in menus])
    else:
        base_menu.extend([(menu.id, menu.name) for menu in menus if menu.id != menu_id])
    return base_menu


def generate_invite_card(user, url):
    """
    created by chenhj at 2017/9/6
    生成邀请卡图片
    """
    cwd = os.path.join(os.getcwd(), 'app/wechat/static')
    bg_img = Image.open('{}/bg.png'.format(cwd))
    draw = ImageDraw.Draw(bg_img)
    font = ImageFont.truetype('{}/LingWaiSC-Medium.otf'.format(cwd), 80)
    draw.text((770, 150), '\n'.join(list(user.nickname)), (0, 0, 0), font=font)

    # 放置指纹图片
    box = (750, 390, 870, 580)
    fingerprint_img = Image.open('{}/fingerprint.png'.format(cwd))
    region = fingerprint_img.resize((box[2] - box[0], box[3] - box[1]))
    bg_img.paste(region, box, mask=region)

    # 放置二维码
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_H,
        box_size=4,
        border=1,
    )
    qr.add_data(url)
    qr.make(fit=True)
    qr_img = qr.make_image()
    qr_img = qr_img.convert("RGBA")
    box = (150, 1555, 450, 1855)
    qr_img = qr_img.resize((box[2] - box[0], box[3] - box[1]))
    bg_img.paste(qr_img, box, mask=qr_img)

    filename = '{}/{}_invite_card.png'.format(cwd, user.id)
    bg_img.save(filename, format='PNG')  # 保存图片
    return filename


def generate_feedback_notify(host, partic, demand, add_point=0):
    """
    create by ld_wu 2017-09-13
    反馈信息微信通知内容
    """
    # 反馈通知与结项使用同一模板
    t = WechatTemplate.get_by_args(code='finish_img_notify')
    # 跳去详情页
    demand_url = urllib.parse.urljoin(
        host, '#DemandDetail?did={d_id}&login_bind=1'.format(d_id=demand.id)
    )
    demand_url = '{host}?redirect_url={url}'.format(
        host=url_for('api_bp.wx_login', _external=True),
        url=urllib.parse.quote_plus(demand_url)
    )
    # oauth = generate_wechat_oauth(url)
    approve_status = (
        '通过' if partic.feedback_status == FeedbackStatus.PASS.value
        else '不通过'
    )
    data = t.content.replace(
        'first_value', '您反馈的信息审核{}\\n'.format(approve_status)
    ).replace(
        'keyword1_value', '{prov}{city}{type}{cate}项目{feedback}'.format(
            prov=demand.prov,
            city=demand.city,
            type=demand.type_display,
            cate=demand.cate_display,
            feedback=', {}'.format(
                Feedback(partic.feedback).display
            ) if partic.feedback else ''
        )
    ).replace(
        'keyword2_value', '审核{}{}'.format(
            approve_status,
            '' if not partic.feedback_refuse_content else ', {}'.format(
                partic.feedback_refuse_content
            )
        )
    )

    if partic.feedback_status == FeedbackStatus.PASS.value:
        if partic.demand_status != DemandStatus.DISPATCHING.value:
            data = data.replace(
                'remark_value', '\\n{}个汇币已返还，可在您的账户中查看，点击查看详情↓↓↓'.format(
                    int(add_point)
                )
            )
        else:
            data = data.replace(
                'remark_value', '\\n已返还1次派单次数，可在您的账户中查看，点击查看详情↓↓↓'
            )
    else:
        data = data.replace(
            'remark_value', '\\n点击查看项目详细↓↓↓'
        )

    return t.template_code, json.loads(data), demand_url
    # return t.template_code, json.loads(data), oauth.authorize_url


def generate_user_level_up_content(
    host, old_user_level, new_user_level, new_user_service
):
    """
    created by chenhj at 12/01/2018

    """
    t = WechatTemplate.get_by_args(code='user_level_up')
    gift_url = urllib.parse.urljoin(host, '#pack/MyPack?login_bind=1')
    gift_url = '{host}?redirect_url={url}'.format(
        host=url_for('api_bp.wx_login', _external=True),
        url=urllib.parse.quote_plus(gift_url)
    )
    data = t.content.replace(
        'first_value', UserLevel(new_user_level).display
    ).replace(
        'keyword1_value', UserLevel(old_user_level).display
    ).replace(
        'keyword2_value', UserLevel(new_user_level).display
    ).replace(
        'remark1_value', UserLevel(new_user_level).display
    ).replace(
        'remark2_value', new_user_service
    )

    return t.template_code, json.loads(data), gift_url


WX_TEMPLATE_FUNC_MAP = {
    'REVIEW_FAIL': generate_review_fail_content,
    'GIFT_NOTIFICATION': generate_gift_pack_content,
    'INVITE_GIFT_NOTIFICATION': generate_invite_gift_pack_content,
    # 结项图片通过审核
    'FINISH_IMG_CHECKED': generate_finish_img_checked_content,
    # 结项图片不通过审核
    'FINISH_IMG_INVALID': generate_finish_img_invalid_content,
    # 反馈审核通知
    'FEEDBACK_NOTIFY': generate_feedback_notify,
    'USER_LEVEL_UP_NOTIFY': generate_user_level_up_content
}
